package cn.com.shopec.erp.product.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;

import cn.com.shopec.erp.common.constant.SZSCMConstant;
import cn.com.shopec.erp.common.page.PageFinder;
import cn.com.shopec.erp.common.page.PageQuery;
import cn.com.shopec.erp.common.utils.JsonHelper2;
import cn.com.shopec.erp.common.utils.LogicUtil;
import cn.com.shopec.erp.common.utils.StringUtil;
import cn.com.shopec.erp.product.model.SpecValOptionInfo;
import cn.com.shopec.erp.product.model.SpecificationDetail;
import cn.com.shopec.erp.product.model.SpecificationInfo;
import cn.com.shopec.erp.product.service.ICommodityCatService;
import cn.com.shopec.erp.product.service.ISpecificationService;
import cn.com.shopec.erp.product.vo.CommodityCatVo;

/**
 * @ClassName: SpecificationController
 * @Description: 货品规格相关的controller
 * @author: lule
 * @date 2013-5-28 下午7:29:43
 * 
 */
@Controller
@RequestMapping("/product/specmgt")
public class SpecificationController {

    private static final Log log = LogFactory.getLog(SpecificationController.class);

    @Resource
    private ISpecificationService specService;

    @Resource
    private ICommodityCatService catService;

    /**
     * @Title: specificationList
     * @Description: 至规格管理——规格列表页面
     * @param modelMap
     * @return
     * @throws Exception
     * @throws
     * @author: lule
     * @date: 2013-5-30下午4:19:11
     */
    @RequestMapping("specList")
    public ModelAndView specificationList(SpecificationInfo specification, ModelMap modelMap) throws Exception {
    	if(!StringUtil.isExist(specification.getCatNo())){
    		specification.setCatNo("0");
    	}
        modelMap.put("specification", specification);
        return new ModelAndView("product/spec/spec_list");
    }

    /**
     * @Title: ajaxToSpecificationList
     * @Description:
     * @param catNo
     * @param pageQuery
     * @param modelMap
     * @return
     * @throws Exception
     * @throws
     * @author: lule
     * @date: 2013-5-30下午4:37:40
     */
    @RequestMapping("ajaxToSpecList")
    @ResponseBody
    public String ajaxToSpecificationList(SpecificationInfo specification, PageQuery pageQuery, ModelMap modelMap)
            throws Exception {
        PageFinder<SpecificationInfo> pageFinder = this.specService.getPagedSpecifications(specification, pageQuery);
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("Rows", pageFinder.getData());
        jsonObj.put("Total", pageFinder.getRowCount());

        return jsonObj.toJSONString();
    }

    /**
     * @Title: toAddSpec
     * @Description: 至新增货品规格页面
     * @param catNo
     * @param modelMap
     * @return
     * @throws Exception
     * @throws
     * @author: lule
     * @date: 2013-5-31上午8:27:42
     */
    @RequestMapping("toAddSpec")
    public ModelAndView toAddSpec(String catNo, ModelMap modelMap) throws Exception {
        SpecificationDetail spec = new SpecificationDetail();
        spec.setCatNo(catNo);
        modelMap.put("spec", spec);
        modelMap.put("opType", "add");

        CommodityCatVo catVo = new CommodityCatVo();
        catVo.setCatPno(SZSCMConstant.CAT_TOP_LEVEL);
        List<CommodityCatVo> catVolist = this.catService.getCommodityCatList(catVo);
        modelMap.put("catVolist", catVolist);

        // return new ModelAndView("product/spec/spec_detail");
        return new ModelAndView("product/spec/add_spec");
    }

    /**
     * @Title: toEditSpec
     * @Description: 到规格编辑页面
     * @param specNo
     * @param modelMap
     * @return
     * @throws Exception
     * @throws
     * @author: lule
     * @date: 2013-6-1上午11:40:04
     */
    @RequestMapping("toEditSpec")
    public ModelAndView toEditSpec(String specNo, ModelMap modelMap) throws Exception {
        SpecificationDetail spec = null;
        try {
            spec = this.specService.getSpecificationDetail(specNo);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        if (spec != null) {
            modelMap.put("spec", spec);
            modelMap.put("opType", "update");
        }

        return new ModelAndView("product/spec/spec_detail");
    }

    /**
     * @Title: toUpdateSpec
     * @Description: 到规格编辑页面
     * @param specNo
     * @param modelMap
     * @return
     * @throws Exception
     * @throws
     * @author: gaoyaxiong
     * @date: 2013-6-1上午11:40:04
     */
    @RequestMapping("toUpdateSpec")
    public ModelAndView toUpdateSpec(String specNo, ModelMap modelMap) throws Exception {
        SpecificationDetail spec = null;
        try {
            spec = this.specService.getSpecificationDetail(specNo);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        if (spec != null) {
            modelMap.put("spec", spec);
            modelMap.put("opType", "update");
        }

        return new ModelAndView("product/spec/update_spec");
    }

    /**
     * @Title: toAddOption
     * @Description: 至新增规格选项值页面
     * @param specNo
     * @param modelMap
     * @return
     * @throws Exception
     * @throws
     * @author: lule
     * @date: 2013-5-31下午8:42:16
     */
    @RequestMapping("toAddOption")
    public ModelAndView toAddOption(String specNo, ModelMap modelMap) throws Exception {
        SpecValOptionInfo option = new SpecValOptionInfo();
        option.setSpecNo(specNo);
        modelMap.put("option", option);
        modelMap.put("opType", "add");
        return new ModelAndView("product/spec/option_detail");
    }

    /**
     * @Title: toEditOption
     * @Description: 至编辑规格选项的页面
     * @param optionNo
     * @param modelMap
     * @return
     * @throws Exception
     * @throws
     * @author: lule
     * @date: 2013-6-1下午1:50:49
     */
    @RequestMapping("toEditOption")
    public ModelAndView toEditOption(String optionNo, ModelMap modelMap) throws Exception {
        SpecValOptionInfo option = null;
        try {
            option = this.specService.getSpecValOption(optionNo);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        if (option != null) {
            modelMap.put("option", option);
            modelMap.put("opType", "update");
        }
        return new ModelAndView("product/spec/option_detail");
    }

    /**
     * @Title: saveSpec
     * @Description: 保存货品规格
     * @param catNo
     * @param specNo
     * @param specName
     * @param modelMap
     * @return
     * @throws Exception
     * @throws
     * @author: lule
     * @date: 2013-6-1上午10:33:03
     */
    @ResponseBody
    @RequestMapping("saveSpec")
    public String saveSpec(String catNo, String specNo, String specName, ModelMap modelMap) throws Exception {
        int res = SZSCMConstant.FAIL_INT;
        String resStr = SZSCMConstant.FAIL;

        if (!StringUtil.isBlank(catNo) && !StringUtil.isBlank(specName)) {
            specNo = specNo == null ? "" : specNo.trim();

            SpecificationInfo spec = new SpecificationInfo();
            spec.setSpecNo(specNo);
            spec.setSpecName(specName.trim());
            spec.setCatNo(catNo.trim());

            try {
                res = this.specService.saveSpecification(spec);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }

            if (res == SZSCMConstant.SUCCESS_INT) {
                specNo = spec.getSpecNo();
                resStr = SZSCMConstant.SUCCESS;
            }
        }

        String json = "{'res':'" + resStr + "', 'specNo':'" + specNo + "'}";
        return json;
    }

    /**
     * @Title: deleteSpec
     * @Description: 删除一个规格
     * @param specNo
     * @param modelMap
     * @return
     * @throws Exception
     * @throws
     * @author: lule
     * @date: 2013-6-1下午3:19:56
     */
    @ResponseBody
    @RequestMapping("deleteSpec")
    public String deleteSpec(String specNo, ModelMap modelMap) throws Exception {
        String resMsg = SZSCMConstant.FAIL;
        int res = SZSCMConstant.FAIL_INT;

        try {
            res = this.specService.delSpecification(specNo);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        switch (res) {
        case SZSCMConstant.SUCCESS_INT:
            resMsg = SZSCMConstant.SUCCESS;
            break;
        case -1:
            resMsg = "操作失败，规格的编号不正确";
            break;
        case -2:
            resMsg = "操作失败，该规格目前正在被使用，不可删除";
            break;
        default:
            ;
        }

        return resMsg;
    }

    /**
     * @Title: saveOption
     * @Description: 保存规格选项
     * @param specNo
     * @param optionNo
     * @param optionName
     * @param modelMap
     * @return
     * @throws Exception
     * @throws
     * @author: lule
     * @date: 2013-5-31下午8:42:02
     */
    @ResponseBody
    @RequestMapping("saveOption")
    public String saveOption(String specNo, String optionNo, String optionName, ModelMap modelMap) throws Exception {
        int res = SZSCMConstant.FAIL_INT;
        String resStr = SZSCMConstant.FAIL;
        if (!StringUtil.isBlank(specNo) && !StringUtil.isBlank(optionName)) {
            optionNo = optionNo == null ? "" : optionNo.trim();

            SpecValOptionInfo option = new SpecValOptionInfo();
            option.setOptionNo(optionNo);
            option.setOptionName(optionName.trim());
            option.setSpecNo(specNo.trim());

            try {
                res = this.specService.saveSpecValOption(option);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }

            if (res == SZSCMConstant.SUCCESS_INT) {
                optionNo = option.getOptionNo();
                resStr = SZSCMConstant.SUCCESS;
            }
        }

        String json = "{'res':'" + resStr + "', 'optionNo':'" + optionNo + "'}";
        return json;
    }

    /**
     * @Title: deleteOption
     * @Description: 删除一个规格选项值
     * @param optionNo
     * @param modelMap
     * @return
     * @throws Exception
     * @throws
     * @author: lule
     * @date: 2013-6-1上午11:54:36
     */
    @ResponseBody
    @RequestMapping("deleteOption")
    public String deleteOption(String optionNo, ModelMap modelMap) throws Exception {
        String resMsg = SZSCMConstant.FAIL;
        int res = SZSCMConstant.FAIL_INT;

        try {
            res = this.specService.delSpecValOption(optionNo); // 删除
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        switch (res) {
        case SZSCMConstant.SUCCESS_INT:
            resMsg = SZSCMConstant.SUCCESS;
            break;
        case -1:
            resMsg = "操作失败，规格选项的编号不正确";
            break;
        case -2:
            resMsg = "操作失败，该规格选值项目前正在被使用，不可删除";
            break;
        default:
            ;
        }

        return resMsg;
    }

    /**
     * 
     * @param catNo
     * @param specNo
     * @param specName
     * @param optionName
     * @return
     * @date gaoyaxiong 2013-6-4
     */
    @RequestMapping("addToSpec")
    @ResponseBody
    public String addToSpec(String catNo, String specNo, String specName, String[] optionName,String[] optionNoold,String[] optionNameold) {
        if (!StringUtil.isBlank(catNo) && !StringUtil.isBlank(specName)) {
            specNo = specNo == null ? "" : specNo.trim();

            SpecificationInfo spec = new SpecificationInfo();
            spec.setSpecNo(specNo);
            spec.setSpecName(specName.trim());
            spec.setCatNo(catNo.trim());

            try {
                int res = this.specService.saveSpecification(spec);
                if (StringUtil.isBlank(specNo)) {
                    specNo = spec.getSpecNo();
                }

                if (res == SZSCMConstant.SUCCESS_INT) {
                	if(optionName != null){
                		for (int i = 0; i < optionName.length; i++) {
                            if (!StringUtil.isBlank(specNo) && !StringUtil.isBlank(optionName[i])) {

                                SpecValOptionInfo option = new SpecValOptionInfo();
                                option.setOptionName(optionName[i].trim());
                                option.setSpecNo(specNo.trim());
                                this.specService.saveSpecValOption(option);
                            }
                        }
                	}
                    
                    if(optionNameold != null && optionNoold != null){
                    	for (int i = 0; i < optionNameold.length; i++) {
                        	SpecValOptionInfo option = new SpecValOptionInfo();
                            option.setOptionNo(optionNoold[i]);
                            option.setOptionName(optionNameold[i].trim());
                            option.setSpecNo(specNo.trim());
                            this.specService.saveSpecValOption(option);
    					}
                    }
                }
                

                    
                
            } catch (Exception e) {
                e.printStackTrace();
                return SZSCMConstant.FAIL;
            }
        } else {
            return SZSCMConstant.FAIL;
        }
        return SZSCMConstant.SUCCESS;
    }

    /**
     * 
     * @param catNo
     * @param response
     * @throws Exception
     * @date gaoyaxiong 2013-6-5
     */
    @RequestMapping("getSpecificationListByCatNo")
    @ResponseBody
    public void getSpecificationListByCatNo(String catNo, HttpServletResponse response) throws Exception {
        List<SpecificationInfo> SpecificationList = this.specService.getSpecifications(catNo);
        if (LogicUtil.isNotNullAndEmpty(SpecificationList)) {
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().append(JsonHelper2.toJson(SpecificationList));
        }
    }

    /**
     * 
     * @param catNo
     * @param response
     * @throws Exception
     * @date gaoyaxiong 2013-6-5
     */
    @RequestMapping("getSpecificationListBySpecNo")
    @ResponseBody
    public void getSpecificationListBySpecNo(String specNo, HttpServletResponse response) throws Exception {
        SpecificationDetail specificationDetail = this.specService.getSpecificationDetail(specNo);
        if (LogicUtil.isNotNull(specificationDetail)) {
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().append(JsonHelper2.toJson(specificationDetail));
        }
    }
}
